package com.lyn.serialPort;

import com.lyn.serialPort.entity.Device;
import com.lyn.serialPort.interfaces.Port;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 串口工厂
 *
 * @author Lyn 2022/12/24
 * @version 1.0.0
 */
public class SerialPortFactory {

    private static final Map<String, Port> portMap = new ConcurrentHashMap<>();

    /**
     * 获取串口
     *
     * @param name     串口名称
     * @return Port
     */
    public static Port get(String name) {
        try {
            Port port = portMap.get(name);
            if (port != null) {
                return port;
            }
            SerialPort serialPort = new SerialPort();
            portMap.put(name,serialPort);
            return serialPort;
        }catch (Throwable e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 关闭串口
     *
     * @param name 串口名称
     * @return true关闭成功 false关闭失败
     */
    public static boolean remove(String name) {
       try {
           Port port = portMap.get(name);
           if (port == null) {
               return false;
           }
           boolean close = port.close();
           portMap.remove(name);
           return close;
       }catch (Throwable e){
           e.printStackTrace();
       }
       return false;
    }

    /**
     * 获取所有串口名称
     *
     * @return 串口名称集合
     */
    public List<String> getAllNames() {
        List<String> stringList = new ArrayList<>();
        try {
            List<Device> deviceList = SerialPortFinder.getDevices();
            for (Device device : deviceList) {
                stringList.add(device.name);
            }
        }catch (Throwable e){
            e.printStackTrace();
        }
        return stringList;
    }

}
